package summary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:30
 * https://leetcode-cn.com/problems/binary-tree-right-side-view/
 */
public class Title199 {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        list.offer(root);
        while (!list.isEmpty()) {
            int size = list.size();
            while (size > 0) {
                TreeNode pop = list.pop();
                size--;
                if (size == 0) {
                    result.add(pop.val);
                }
                if (pop.left != null) {
                    list.add(pop.left);
                }
                if (pop.right != null) {
                    list.add(pop.right);
                }
            }
        }
        return result;
    }


    public List<Integer> rightSideView1(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        list.offer(root);
        while (!list.isEmpty()) {
            int size = list.size();
            for (int i = 0; i < size; i++) {
                TreeNode pop = list.pop();
                if (pop.left != null) {
                    list.offer(pop.left);
                }
                if (pop.right != null) {
                    list.offer(pop.right);
                }
                if (i == size - 1) {
                    result.add(pop.val);
                }
            }
        }
        return result;
    }


    public List<Integer> rightSideView2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        dfs(root, result, 0);
        return result;
    }

    private void dfs(TreeNode root, List<Integer> result, int depth) {
        if (root == null) {
            return;
        }
        if (result.size() == depth) {
            result.add(root.val);
        }
        depth++;
        dfs(root.right, result, depth);
        dfs(root.left, result, depth);
    }


    public static void main(String[] args) {

    }
}
